package cn.bon.user.service.security;


import cn.bon.user.mapper.RoleMapper;
import cn.bon.user.mapper.RoleUserMapper;
import cn.bon.user.mapper.UserMapper;
import cn.bon.user.pojo.po.RolePo;
import cn.bon.user.pojo.po.RoleUserPo;
import cn.bon.user.pojo.po.UserPo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

/**
 * @author: dronff
 * @description:
 * @CreateTime: 2023/12/8 10:14
 **/
@Service
@AllArgsConstructor
public class UserAuthenticServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleUserMapper roleUserMapper;
    @Resource
    private RoleMapper roleMapper;
    @Override
    public UserDetails loadUserByUsername(String username) {
        UserPo userPo = userMapper.selectOne(
                new QueryWrapper<UserPo>()
                        .eq("username", username)
        );
        if (userPo == null) {
            throw new UsernameNotFoundException("密码错误");
        }
        User.UserBuilder userBuilder = User.withUsername(userPo.getUsername())
                .password(userPo.getPassword())
                .authorities("simple");

        // 获取当前用户的权限
        List<RoleUserPo> userRoleIds = roleUserMapper.selectList(
                new QueryWrapper<RoleUserPo>()
                        .eq("user_id", userPo.getUserId())
        );
        if (userRoleIds != null && !userRoleIds.isEmpty()) {
            QueryWrapper<RolePo> rolePoQueryWrapper = new QueryWrapper<>();
            for (int i = 0; i < userRoleIds.size(); i++) {
                rolePoQueryWrapper.or()
                        .eq("role_id",userRoleIds.get(i).getRoleId());
            }
            // 当前用户的权限
            List<RolePo> rolePos = roleMapper.selectList(rolePoQueryWrapper);
            String[] roleStrList = new String[rolePos.size()];
            int i=0;
            for(Iterator<RolePo> rolePoIterator = rolePos.iterator();rolePoIterator.hasNext();){
                roleStrList[i++] = rolePoIterator.next().getRoleName();
            }
            userBuilder.roles(roleStrList);
        }
        return userBuilder.build();
    }
}
